package com.lee.auth.security.config;

import lombok.AccessLevel;
import lombok.AllArgsConstructor;
import org.springframework.util.AntPathMatcher;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.function.BiConsumer;

/**
 * @author lee HN
 * @date 2021/4/12 15:11
 */
@AllArgsConstructor(access = AccessLevel.PACKAGE)
public final class PathHandler {

    private final BiConsumer<HttpServletRequest, HttpServletResponse> handler;
    //如果为长度为0  表示所有路径都要处理
    private final String[] patterns;

    private static final AntPathMatcher Matcher = new AntPathMatcher();

    public boolean handle(HttpServletRequest request, HttpServletResponse response) {
        if (patterns == null || patterns.length == 0) {
            handler.accept(request, response);
            return true;
        }
        String path = request.getServletPath();
        for (String pattern : patterns)
            if (Matcher.matchStart(pattern, path)) {
                handler.accept(request, response);
                return true;
            }
        return false;
    }

}
